package com.grandbroad.eim.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.grandbroad.eim.R;

import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;

/**
 * 聊天视图适配器
 */
public class ChatListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<Message> messageList = new ArrayList<>();

    public void setMessageList(List<Message> messageList) {
        this.messageList = messageList;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.chat_item, viewGroup, false);
        return new ChatItemViewholder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
        if (viewHolder instanceof ChatItemViewholder)
        {
            Message message = messageList.get(i);
            ChatItemViewholder itemViewholder = (ChatItemViewholder) viewHolder;
            UserInfo u_info = message.getFromUser();
            itemViewholder.tvChatName.setText(u_info.getNickname());
            TextContent content = (TextContent) message.getContent();
            itemViewholder.tvChatContent.setText(content.getText());
            x.image().bind(itemViewholder.imgUserAvatar,u_info.getAvatar());
            UserInfo info = JMessageClient.getMyInfo();
            if (info.getUserID()==u_info.getUserID())
            {
                //自己说的fa
                itemViewholder.tvChatContent.setBackgroundResource(R.drawable.chat_my_bg);
            }
            else
            {
                //别人说的fa
                itemViewholder.tvChatContent.setBackgroundResource(R.drawable.chat_other_bg);
            }
        }

    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }

    /**
     * 聊天室item
     */
    class ChatItemViewholder extends RecyclerView.ViewHolder {
        @BindView(R.id.img_user_avatar)
        ImageView imgUserAvatar;
        @BindView(R.id.tv_chat_name)
        TextView tvChatName;
        @BindView(R.id.tv_chat_content)
        TextView tvChatContent;
        public ChatItemViewholder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);
        }
    }
}
